
package com.probiz.estore.customer.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.probiz.estore.Constants;
import com.probiz.estore.aop.VerFuncInterceptor;
import com.probiz.estore.common.model.customer.Customer;
import com.probiz.estore.common.model.customer.Membership;
import com.probiz.estore.core.search.SearchCriteria;
import com.probiz.estore.customer.service.CustomerManager;
import com.probiz.estore.customer.service.CustomerNtManager;
import com.probiz.estore.customer.service.MembershipManager;
import com.probiz.estore.system.service.MsgSendManager;
import com.probiz.estore.system.util.MsgTemplateConstants;

public class CustomerNtManagerImpl implements CustomerNtManager {
	protected final transient Log	logger	= LogFactory.getLog(getClass());

	private CustomerManager			customerManager;

	private MembershipManager		membershipManager;

	private MsgSendManager			msgSendManager;

	public void setCustomerManager(CustomerManager customerManager) {
		this.customerManager = customerManager;
	}

	public void setMembershipManager(MembershipManager membershipManager) {
		this.membershipManager = membershipManager;
	}

	public void setMsgSendManager(MsgSendManager msgSendManager) {
		this.msgSendManager = msgSendManager;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.customer.service.CustomerNtManager#upgradeMembershipLevelJob()
	 */
	public void upgradeMembershipLevelJob() {
		// 判断软件版本，如果是大众版，本方法不会被执行
		try {
			if (!VerFuncInterceptor.getInstance().invoke(
					VerFuncInterceptor.Constants.membershipAutoUpgrade)) {
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		List<Membership> memberShipList = null; // 用于记录当前store的membership列表
		memberShipList = membershipManager.listAllOrdered("upgradeShopPoint", false);
		Integer currentStoreId = null; // 用于标识当前store
		String hql = " from Customer c where c.status=1 and c.appuserId!=-2 and c.userType="+Customer.USER_TYPE_CUSTOMER+" and c.deleted=0 order by c.appuserId desc";
		boolean flag = true;
		int pageSize = 10;
		int pageNo = 1;
		do {
			// 数据级大时可以考虑只扫描几天内更新的
			SearchCriteria sc = SearchCriteria.getHqlPagingInstance(hql, null,
					pageNo, pageSize, null);
			List<Customer> customerList = customerManager.searchByCriteria4MembershipLevel(sc);
			if (customerList.size() > 0) {

				for (Customer customer : customerList) {
					
					try{
						if(customer.getCustomerId().equals(Constants.USERID_ANONYMOUS)){
							// --------错误控制------
							continue;
						}
						if (customer.getMembershipId() == null ) {
							// --------错误控制------
							logger.error("customer " + customer.getId()
									+ " doesn't have membership");
							continue;
						}
						Membership perMembership = null;
						for (Membership memberShip : memberShipList) {
							if (memberShip.getMembershipId().equals(customer.getMembershipId())) {
								perMembership = memberShip;
								break;
							}
						}
						if (perMembership == null) {
							// --------错误控制------
							logger.error("customer " + customer.getId()
									+ " doesn't have corresponding membership");
							continue;
						}
						for (Membership memberShip : memberShipList) {
							int upgradeShopPoint = memberShip.getUpgradeShopPoint();
							// 向高一级别等级升级、如果是匿名顾客的话就不用比较了.或者如果升级为-1表示不支持自动升级
							if (memberShip.getUpgradeShopPoint().compareTo(
									perMembership.getUpgradeShopPoint()) <= 0
									|| memberShip.getMembershipLevel().intValue() == -2
									|| upgradeShopPoint == -1) {
								continue;
							}
							// 会员等级不等于之前的会员等级(相同的会员等级就不需要升级了)
							if (customer.getMembershipId().intValue() == memberShip
									.getMembershipId().intValue()) {
								break;
							}
							
							if (customer.getShopPoint().getGainedTotal() >= upgradeShopPoint) {
								// case:如果获得总积分>=升级积分,获取MembershipId更新客户的会员等级.
									customer.setMembershipId(memberShip.getMembershipId());
									customerManager.update(customer);
									Map<String, Object> model = new HashMap<String, Object>();
									model.put("upgradeShopPoint", customer.getShopPoint().getGainedTotal());
									model.put("perMembershipName", perMembership.getMembershipName());
									model.put("aftMembershipName", memberShip.getMembershipName());
									model.put("userName", customer.getFullName());
									msgSendManager.sendMsg(MsgTemplateConstants.MESSAGE_MEMBER_UPDATE_GRADE, model, new String[]{customer.getEmail()},null == customer.getAppuserId() ? null : new String[]{customer.getAppuserId().toString()}, null == customer.getMobilephone() ? null : new String[]{customer.getMobilephone()} );
									break;
							} else {
								// case:否则 继续下一个升级积分较低的等级
								continue;
							}
						}
					}catch(Exception e){
						e.printStackTrace();
					}

				}

			}
			if (customerList.size() != pageSize) {
				flag = false;
			} else {
				++pageNo;
			}
		} while (flag);

	}
	

}
